from fastapi import Request, status
from fastapi.responses import JSONResponse
from tortoise.exceptions import DoesNotExist, IntegrityError
import logging

logger = logging.getLogger(__name__)

async def exception_handler(request: Request, exc: Exception):
    """全局异常处理"""
    if isinstance(exc, DoesNotExist):
        return JSONResponse(
            status_code=status.HTTP_404_NOT_FOUND,
            content={
                "code": 404,
                "message": "资源未找到",
                "detail": str(exc)
            }
        )
    
    if isinstance(exc, IntegrityError):
        return JSONResponse(
            status_code=status.HTTP_400_BAD_REQUEST,
            content={
                "code": 400,
                "message": "数据完整性错误",
                "detail": str(exc)
            }
        )
    
    # 记录未处理的异常
    logger.error(f"未处理的异常: {str(exc)}", exc_info=True)
    return JSONResponse(
        status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
        content={
            "code": 500,
            "message": "服务器内部错误",
            "detail": str(exc)
        }
    ) 